package cn.zh.stan.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.hankkin.library.RefreshSwipeMenuListView;
import com.hankkin.library.SwipeMenu;
import com.hankkin.library.SwipeMenuCreator;
import com.hankkin.library.SwipeMenuItem;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import cn.zh.stan.BaseUrl;
import cn.zh.stan.ITem.CAItem;
import cn.zh.stan.MyApplication;
import cn.zh.stan.R;
import cn.zh.stan.activity.DtailGoods;
import cn.zh.stan.activity.FilOrder;
import cn.zh.stan.activity.MainActivity;
import cn.zh.stan.adapter.CarAdapter;
import cn.zh.stan.util.ToastUtil;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class CarFragment extends Fragment implements View.OnClickListener,RefreshSwipeMenuListView.OnRefreshListener{

    TextView goOrder;
    RefreshSwipeMenuListView swipe;
    CarAdapter carAdapter;
    ArrayList<CAItem> caItems=new ArrayList<CAItem>();
    ArrayList<CAItem> datas=new ArrayList<CAItem>();
    MainActivity activty;
    String uid;
    CheckBox allchose;
    MyApplication mapp;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_car,container,false);
        mapp= (MyApplication) getActivity().getApplication();
        initv(view);
        return view;
        }

      public void initv(View view){
          goOrder=view.findViewById(R.id.goOrder);
          swipe=view.findViewById(R.id.swipe);
          activty= (MainActivity) getActivity();
          allchose=view.findViewById(R.id.allchose);
          uid=activty.getUid();
          SwipeMenuCreator creator = new SwipeMenuCreator() {
              @Override
              public void create(SwipeMenu menu) {
//                // 创建滑动选项
                  // 创建删除选项
                  SwipeMenuItem argeeItem = new SwipeMenuItem(getActivity().getApplicationContext());
                  argeeItem.setBackground(new ColorDrawable(getResources().getColor(R.color.del)));
                  argeeItem.setWidth(dp2px(80, getActivity().getApplicationContext()));
                  argeeItem.setTitle("删除");
                  argeeItem.setTitleSize(16);
                  argeeItem.setTitleColor(Color.WHITE);
                  menu.addMenuItem(argeeItem);
                 }
                };
          swipe.setMenuCreator(creator);

          swipe.setOnMenuItemClickListener(new RefreshSwipeMenuListView.OnMenuItemClickListener() {
              @Override
              public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                  switch (index) {
                      case 0: //第一个选项
                          del(position,swipe.getChildAt(position+1-swipe.getFirstVisiblePosition()));
                          break;
                   }
                }
              });

          swipe.setOnItemClickListener(new AdapterView.OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                  Intent intent=new Intent(getActivity(),DtailGoods.class);
                 getActivity().startActivity(intent);
                }
          });
          goOrder.setOnClickListener(this);

          carAdapter=new CarAdapter(getActivity(),caItems,allchose,mapp);
          swipe.setAdapter(carAdapter);
          swipe.setOnRefreshListener(this);
          allchose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
              @Override
              public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                  if (mapp.isIschose()) {
                      if (b) {
                          for (int i = 0; i < caItems.size(); i++) {
                              caItems.get(i).setType(true);
                          }
                      } else {
                          for (int i = 0; i < caItems.size(); i++) {
                              caItems.get(i).setType(false);
                          }
                        }
                      carAdapter.notifyDataSetChanged();
                  }else {
                      mapp.setIschose(true);
                  }
                 }
            });

          }

    @Override
    public void onResume() {
        super.onResume();
        getPost();
    }

    @Override
    public void onClick(View view) {
        int id=view.getId();
        switch (id){
            case R.id.goOrder:
                datas.clear();
                   for (int i=0;i<caItems.size();i++){
                       if (caItems.get(i).isType()){
                         datas.add(caItems.get(i));
                       }
                   }
                if (datas.size()>0){
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cd", datas);
                    intent.setClass(getActivity(), FilOrder.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else {
                    ToastUtil.showShort(getActivity(),"你还没选择商品哦");
                  }
                break;
            }
          }

  //relistview刷新
    public  int dp2px(int dp, Context context) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                context.getResources().getDisplayMetrics());
            }


    private void del(final int index, View v){
        final Animation animation = (Animation) AnimationUtils.loadAnimation(v.getContext(), R.anim.list_anim);
        animation.setAnimationListener(new Animation.AnimationListener() {
            public void onAnimationStart(Animation animation) {}
            public void onAnimationRepeat(Animation animation) {}
            public void onAnimationEnd(Animation animation) {
                caItems.remove(index);
                carAdapter.notifyDataSetChanged();
                animation.cancel();
            }
        });
        v.startAnimation(animation);
      }

    @Override
    public void onRefresh() {
        swipe.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe.complete();
                Toast.makeText(getActivity(),"已完成",Toast.LENGTH_SHORT).show();

            }
        },2000);
       }

    @Override
    public void onLoadMore() {
        swipe.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe.complete();
                Toast.makeText(getActivity(),"已完成",Toast.LENGTH_SHORT).show();
            }
        },2000);
       }




       //请求购物车列表
       public void getPost(){
           OkHttpUtils.get(BaseUrl.goods_car)
                   .params("userId",uid)
                   .execute(new StringCallback() {
                       @Override
                       public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                           try {
                               JSONObject js=new JSONObject(s);
                               boolean State=js.getBoolean("State");
                               if (State){
                                   JSONArray ja=js.getJSONArray("Data");
                                   caItems.clear();
                                   for (int i=0;i<ja.length();i++){
                                      JSONObject jo=ja.getJSONObject(i);
                                      String id=jo.getString("Id");
                                      String GoodsId=jo.getString("GoodsId");
                                      String UserId=jo.getString("UserId");
                                      int  Num=jo.getInt("Num");
                                      String GoodsNo=jo.getString("GoodsNo");
                                      String GoodsName=jo.getString("GoodsName");
                                      String Unit=jo.getString("Unit");
                                      double Price_Detail=jo.getDouble("Price_Detail");
                                      CAItem caItem=new CAItem(id,GoodsId,Num,GoodsNo,GoodsName,Unit,Price_Detail,false);
                                      caItems.add(caItem);
                                     }
                                   carAdapter.notifyDataSetChanged();

                               }

                           } catch (JSONException e) {
                               e.printStackTrace();
                           }
                       }
                       @Override
                       public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                           super.onError(isFromCache, call, response, e);
                       }
                   });
              }
        }
